package com.pat.manager;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.pat.om.Location;
import com.pat.utils.HibernateUtil;

public class LocationManager {

	public List get() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		List result = session.createCriteria(Location.class).list();
		session.getTransaction().commit();

		return result;
	}

	public List get(int cellNo) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();

		String hql = "FROM Location a WHERE a.cellNo = :cell_No";
		Query query = session.createQuery(hql);
		query.setParameter("cell_No", cellNo);
		List results = query.list();

		session.getTransaction().commit();

		return results;
	}

	public void post(int cellNo, String latitude, String longtitude,
			Date timestamp) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();

		Location location = new Location();
		location.setCellNo(cellNo);
		location.setLatitude(latitude);
		location.setLongtitude(longtitude);
		location.setTimestamp(timestamp);
		session.delete(location);
		session.save(location);

		session.getTransaction().commit();
	}

	public void post(Location location) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		session.delete(location);
		session.save(location);
		session.getTransaction().commit();

	}

	public int delete(int cellNo) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();

		String hql = "delete from Location a where a.cellNo = :cell_No";
		Query query = session.createQuery(hql);
		query.setParameter("cell_No", cellNo);
		int rowCount = query.executeUpdate();
		session.getTransaction().commit();
		return rowCount;

	}

	public void deleteCurrentLocation(Location location) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		session.delete(location);
		session.getTransaction().commit();
	}

	public void put(Location location) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		session.update(location);
		session.getTransaction().commit();

	}

}
